<template>
  <div>
    <HeaderNav />
    <div class="message-center">
      <el-tabs v-model="activeTab" type="card">
        <!-- 消息列表标签页 -->
        <el-tab-pane label="消息列表" name="list">
          <el-row :gutter="20">
            <!-- 左侧导航 -->
            <el-col :span="4">
              <div class="side-nav">
                <!-- 日期显示区域 -->
                <div class="date-section">
                  <div class="date-display">
                    <div class="date-main">{{ currentDate }}</div>
                    <div class="date-week">{{ currentWeek }}</div>
                  </div>
                </div>

                <!-- 分组消息区域 -->
                <div class="messages-section">
                  <div class="group-title">消息分组</div>
                  <ul class="messages-group">
                    <li
                      v-for="(group, index) in messageGroups"
                      :key="index"
                      :class="{ active: currentNav === group.key }"
                      @click="selectNav(group.key)"
                    >
                      <i :class="group.icon"></i>
                      <span>{{ group.name }}</span>
                      <span class="count" v-if="group.count">({{ group.count }})</span>
                    </li>
                  </ul>
                </div>
              </div>
            </el-col>

            <!-- 主内容区 -->
            <el-col :span="20">
              <div class="main-content">
                <!-- 消息列表 -->
                <div class="message-table">
                  <ElTable
                    :data="filteredMessages"
                    :columns="tableColumns"
                    :loading="loading"
                    :pagination="paginationConfig"
                    :show-action="true"
                    action-label="操作"
                    :action-width="120"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  >
                    <template #status="{ row }">
                      <el-tag :type="row.status === 'read' ? 'success' : 'warning'">
                        {{ row.status === 'read' ? '已读' : '未读' }}
                      </el-tag>
                    </template>
                    <template #action="{ row }">
                      <el-button type="primary" link @click="showMessageDetail(row)">查看</el-button>
                      <el-button type="danger" link @click="deleteMessage(row.id)">删除</el-button>
                    </template>
                  </ElTable>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 消息详情弹窗 -->
          <el-dialog
            v-model="detailVisible"
            title="消息详情"
            width="600px"
            @close="closeDetail"
          >
            <div v-if="currentMessage">
              <p><strong>发件人:</strong> {{ currentMessage.sender_name || currentMessage.sender }}</p>
              <p><strong>标题:</strong> {{ currentMessage.title }}</p>
              <p><strong>时间:</strong> {{ formatDate(currentMessage.created_at) }}</p>
              <p><strong>状态:</strong> {{ currentMessage.status === 'read' ? '已读' : '未读' }}</p>
              <p><strong>内容:</strong></p>
              <div class="message-content">{{ currentMessage.content }}</div>
            </div>
          </el-dialog>

          <!-- 删除确认弹窗 -->
          <BaseModal
            :visible="deleteModalVisible"
            title="删除确认"
            @update:visible="deleteModalVisible = $event"
            @confirm="confirmDelete"
          >
            <p>确定要删除这条消息吗？此操作不可恢复！</p>
          </BaseModal>
        </el-tab-pane>

        <!-- 发送消息标签页（仅管理员可见） -->
        <el-tab-pane label="发送消息" name="send" v-if="isAdmin">
          <MessageSender @message-sent="handleMessageSent" />
        </el-tab-pane>


      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import HeaderNav from '@/components/HeaderNav.vue'
import ElTable from '@/components/Table/ElTable.vue'
import BaseModal from '@/components/Modal/BaseModal.vue'
import MessageSender from './components/MessageSender.vue'
import { getMessageList, markMessageAsRead, deleteMessage as deleteMessageApi } from '@/api/messages'
import { ElMessage } from 'element-plus'

// 用户状态管理
const userStore = useUserStore()

// 响应式数据定义
const activeTab = ref('list')
const currentNav = ref('all')
const detailVisible = ref(false)
const deleteModalVisible = ref(false)
const currentMessage = ref(null)
const messages = ref([])
const loading = ref(false)
const deleteMessageId = ref(null)


// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算属性：分页配置
const paginationConfig = computed(() => ({
  currentPage: pagination.value.currentPage,
  pageSize: pagination.value.pageSize,
  total: pagination.value.total,
  pageSizes: [10, 20, 50],
  layout: 'total, sizes, prev, pager, next, jumper'
}))

// 消息分组
const messageGroups = ref([
  { key: 'all', name: '全部消息', icon: 'el-icon-message', count: 0 },
  { key: 'unread', name: '未读消息', icon: 'el-icon-message-solid', count: 0 },
  { key: 'read', name: '已读消息', icon: 'el-icon-check', count: 0 }
])

// 表格列配置
const tableColumns = [
  { prop: 'sender_name', label: '发件人', width: 120 },
  { prop: 'title', label: '标题', minWidth: 200 },
  { prop: 'created_at', label: '时间', width: 180 },
  { prop: 'status', label: '状态', width: 100, slotName: 'status' }
]

// 计算属性：过滤后的消息列表
const filteredMessages = computed(() => {
  // 处理全部/已读/未读分组筛选
  switch (currentNav.value) {
    case 'all':
      return messages.value
    case 'unread':
      return messages.value.filter(msg => msg.status === 'unread')
    case 'read':
      return messages.value.filter(msg => msg.status === 'read')
    default:
      return messages.value
  }
})

// 计算属性：各分组消息数量
const groupCounts = computed(() => ({
  all: messages.value.length,
  unread: messages.value.filter(msg => msg.status === 'unread').length,
  read: messages.value.filter(msg => msg.status === 'read').length
}))

// 计算属性：是否为管理员
const isAdmin = computed(() => userStore.isAdmin)

// 计算属性：当前日期（格式：YYYY-MM-DD）
const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
})

// 计算属性：当前星期
const currentWeek = computed(() => {
  const weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weeks[new Date().getDay()]
})

// 方法：切换左侧导航
const selectNav = (navKey) => {
  currentNav.value = navKey
}

// 方法：显示消息详情
const showMessageDetail = async (message) => {
  currentMessage.value = message
  detailVisible.value = true

  // 标记为已读
  if (message.status === 'unread') {
    try {
      const response = await markMessageAsRead(message.id)
      if (response.code === 200) {
        message.status = 'read'
        // 更新分组计数
        updateGroupCounts()
      }
    } catch (error) {
      console.error('标记消息为已读失败:', error)
    }
  }
}
const deleteMessage = (id) => {
  deleteMessageId.value = id
  deleteModalVisible.value = true
}

const confirmDelete = async () => {
  try {
    const response = await deleteMessageApi(deleteMessageId.value)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchMessages()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  } finally {
    deleteModalVisible.value = false
  }
}
// 方法：关闭消息详情弹窗
const closeDetail = () => {
  currentMessage.value = null
  detailVisible.value = false
}

// 方法：处理分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  pagination.value.currentPage = 1
  fetchMessages()
}

// 方法：处理当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchMessages()
}

// 方法：更新分组计数
const updateGroupCounts = () => {
  messageGroups.value.forEach(group => {
    group.count = groupCounts.value[group.key] || 0
  })
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 方法：获取消息列表（真实数据）
const fetchMessages = async () => {
  try {
    loading.value = true

    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    // 添加状态筛选
    if (currentNav.value !== 'all') {
      params.status = currentNav.value
    }

    const response = await getMessageList(params)

    if (response.code === 200 && response.data) {
      messages.value = response.data.list || []
      pagination.value.total = response.data.pagination?.total || 0
    } else {
      ElMessage.error(response.message || '获取消息列表失败')
    }
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
    // 更新分组计数
    updateGroupCounts()
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMessages()
})



// 监听groupCounts变化，更新联系人分组的数量显示
watch(groupCounts, (newCounts) => {
  messageGroups.value.forEach(group => {
    group.count = newCounts[group.key] || 0
  })
}, { immediate: true, deep: true })

// 监听currentNav变化，重新获取数据
watch(currentNav, () => {
  pagination.value.currentPage = 1
  fetchMessages()
})

// 处理消息发送完成事件
const handleMessageSent = () => {
  // 切换回消息列表标签页
  activeTab.value = 'list'
  // 刷新消息列表
  fetchMessages()
}




</script>

<style lang="scss" scoped>
.message-center {
  height: 100vh;

  // 左侧导航样式
  .side-nav {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 20px 0;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 100vh;

    // 日期显示区域
    .date-section {
      padding: 0 20px 20px;
      border-bottom: 1px solid #eee;
      margin-bottom: 20px;

      .date-display {
        text-align: center;

        .date-main {
          font-size: 1.2rem;
          font-weight: 600;
          color: #333;
          margin-bottom: 5px;
        }

        .date-week {
          font-size: 0.9rem;
          color: #999;
        }
      }
    }

    // 消息分组区域
    .messages-section {
      padding: 0 20px;

      .group-title {
        font-size: 0.9rem;
        color: #999;
        margin-bottom: 15px;
        text-transform: uppercase;
        letter-spacing: 1px;
      }

      .messages-group {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
          display: flex;
          align-items: center;
          padding: 12px 15px;
          border-radius: 6px;
          cursor: pointer;
          transition: all 0.3s ease;
          margin-bottom: 5px;

          &:hover {
            background-color: #f5f7fa;
          }

          &.active {
            background-color: #ecf5ff;
            color: #409eff;
            font-weight: 500;
          }

          i {
            margin-right: 10px;
            font-size: 1.1rem;
          }

          .count {
            margin-left: auto;
            font-size: 0.8rem;
            color: #999;
          }
        }
      }
    }
  }

  // 主内容区样式
  .main-content {
    padding: 20px;

    .message-table {
      background-color: #ffffff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  // 消息详情内容样式
  .message-content {
    margin-top: 10px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    line-height: 1.6;
    white-space: pre-wrap;
  }
}
</style>
